import { TreeDataProvider, Event, TreeItem, TreeItemCollapsibleState, ProviderResult,window } from "vscode";
import { readPathsSigns } from './inc/readPathsSigns';
import * as vscode from 'vscode';
import * as fs from 'fs';
import { glob } from "glob";
import { promises } from "dns";

export class TreeViewProvider implements TreeDataProvider<DataItem> {
    data: DataItem[];

    constructor() {
        this.data = [];
    }  
    
    private _onDidChangeTreeData: vscode.EventEmitter<DataItem | undefined> = new vscode.EventEmitter<DataItem | undefined>();
    readonly onDidChangeTreeData: vscode.Event<DataItem | undefined> = this._onDidChangeTreeData.event;
  
    public refresh( item : DataItem |undefined  ): void {
      this._onDidChangeTreeData.fire( item );
    }

    loadItems(){
        this.data = [];
        let rootpath = vscode.workspace.rootPath;
        let data:any = "" , map: { name: string; options: any; }[] = [];
        let ready = true;
        if( rootpath ){
            if( fs.existsSync(rootpath + "\\.lproject.json" ) ){
                data = fs.readFileSync(rootpath + "\\.lproject.json","utf-8");
                data = JSON.parse( data );
                for(let key in data){
                    // map.set( key , data[key] || {} );
                    map.push( { name : key , options : data[key] } );
                }
            }else{
                ready = false;
                vscode.window.showWarningMessage('找不到配置文件 .lproject.json');
            }
        }else{
            ready = false;
            vscode.window.showWarningMessage('您还没有打开项目(WorkSpace is null)');
        }

        const update = ( i : any )=>{
            if(Number(i)>= map.length) {
                this.refresh( undefined );
                return;
            }

            let d = map[i];
            if( d.options.url ){
                let element = new DataItem( d.name , undefined , d.options );            
                this.data.push( element );
                update( Number(i) + 1);
                return;
            }

            let element = new DataItem( d.name , [] , d.options );            
            this.data.push( element );

            if(element && element.options && element.options?.paths && element.options.paths?.length>0){            
                let signs = readPathsSigns( element );
                signs.then((res)=>{
                    for(let x in res){

                        let title = String(res[x].text).split("=>");
                        let tmpele : DataItem|null;
                        if(title.length === 2){
                            tmpele = (()=>{
                                if(element.children){
                                    for(let j in element.children){
                                        if( element.children[j].label === String(title[0]).trim() ){
                                            return element.children[j];
                                        }
                                    }
                                }
                                return null;
                            })();
                            if( tmpele ){
                                tmpele.children?.push( new DataItem(String(title[1]).trim() , undefined , res[x] , res[x].file.path ));
                                continue;
                            }else{
                                tmpele = new DataItem( String(title[0]).trim() , [] , d.options );
                                tmpele.children?.push( new DataItem(String(title[1]).trim() , undefined , res[x] , res[x].file.path ));
                            }
                        }
                        // else if(title.length > 2){
                        //     tmpele = (()=>{
                        //         let mbele :any = null;
                        //         for(let i=0; i<title.length; i++){
                        //             mbele = null;
                        //             if(element.children){
                        //                 for(let j in element.children){
                        //                     if( element.children[j].label === String(title[i]).trim() ){
                        //                         mbele = element.children[j];
                        //                         break;
                        //                     }
                        //                 }
                        //                 if(!mbele && Number(i) < title.length-1){
                        //                     mbele = new DataItem(String(title[i]).trim() , [] , res[x] , res[x].file.path );
                        //                     element.children?.push( mbele );
                        //                 }else if( !mbele ){
                        //                     mbele = new DataItem(String(title[i]).trim() , undefined , res[x] , res[x].file.path );
                        //                     element.children?.push( mbele );
                        //                 }
                        //             }
                        //         }
                        //         return null;
                        //     })();
                        //     this.refresh( element );
                        //     return;
                        // }
                        else{
                            tmpele = new DataItem(String(title[0]).trim() , undefined , res[x] , res[x].file.path );
                        }

                        element.children?.push( tmpele );
                    }
                    update( Number(i) + 1);
                    this.refresh( element );
                });
            }else{
                update( Number(i) + 1);
                // element && this.refresh( element );
            }
        };

        ready && update(0);
        
    }

    getTreeItem(element: DataItem): TreeItem | Thenable<TreeItem> {
        return element;
    }

    getChildren(element?: DataItem | undefined): ProviderResult<DataItem[]> {
        if (element === undefined) {
            return this.data;
        }
        // element.children?.push(new DataItem('temp-sub') );
        return element.children;
    }

    public static initTreeViewItem(){
        const treeViewProvider = new TreeViewProvider();
        treeViewProvider.loadItems();
        window.registerTreeDataProvider('treeView-item',treeViewProvider);

		vscode.commands.registerCommand('treeView-item.refreshEntry', () =>
            //treeViewProvider.refresh( undefined )
            treeViewProvider.loadItems()
		);
    }
}


export class DataItem extends TreeItem{
    constructor(
        public readonly label: string, 
        public children?: DataItem[] | undefined , 
        public options? : any | undefined,
        public tips? : string | undefined
    ) {
        super(label, children === undefined ? TreeItemCollapsibleState.None : TreeItemCollapsibleState.Collapsed);
        this.children = children;
        this.options = options;
    }

    command = {
        title: `${this.label}`,
        command: 'itemClick',
        tooltip: this.tips || this.label,
        arguments: [
            this
        ]
    };
}